#!/usr/bin/python3
# -*- coding: utf-8 -*-

import getpass
import socket,random
from config import DEPLOY_ROOT_PATH
from config.logger import logger
from config.load_conf import GlobalConf
from config.conf_ansible import ConfAnsibleInventory


# 固定随机数种子，支持重入执行
random.seed(socket.gethostname())


class ConfigureAnsibleInventory:

    def __init__(self):
        # 读取conf file
        self.conf_map = GlobalConf.get_map()

    def config_ansible_vars(self):
        ansible_vars_map = ConfAnsibleInventory.get_vars_map()
        logger.info("ansible vars: {}".format(ansible_vars_map))
        ansible_vars_map["all"]["data_dirs"] = self.conf_map["dirs"]
        ansible_vars_map["all"]['ansible_user'] = getpass.getuser()
        ConfAnsibleInventory.write_vars_map(ansible_vars_map)

    def config_ansible_hosts(self):
        inventory_conf = ConfAnsibleInventory()
        candidate_nodes = self.conf_map["nodes"]
        logger.info("Write all deploy nodes to ansible host[nodes] - {}".format(candidate_nodes))
        inventory_conf.write_ansible_hosts("nodes", candidate_nodes)

        # other modules
        for component in ["docker", "mysql", "redis", "mongodb", "hivemq", "clickhouse", "postgresql", "neo4j"]:
            logger.info("Write nodes to ansible host[{}] - {}".format(component, candidate_nodes))
            inventory_conf.write_ansible_hosts(component, candidate_nodes)

        # docker registry
        registry_node = random.choice(candidate_nodes)
        logger.info("Write nodes to ansible host[registry] - {}".format(registry_node))
        inventory_conf.write_ansible_hosts('registry', [registry_node])


    def run(self):
        # 复写ansible vars
        self.config_ansible_vars()
        # 给各hosts分配IP
        self.config_ansible_hosts()


if __name__ == '__main__':
    logger.info(f"Deploy root path: {DEPLOY_ROOT_PATH}")
    logger.info("**************Configure ansible inventory hosts and vars*****************")
    configure_inventory = ConfigureAnsibleInventory()
    configure_inventory.run()
